#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __author__=LuLu
import functools
import traceback
import logging
from logging.handlers import TimedRotatingFileHandler


# def log(func):
#     @functools.wraps(func)
#     def wrapper(*args, **kwargs):
#         print('\n==============================================\n已执行---> %s():' % func.__name__)
#         print('用例备注---> %s' % func.__doc__)
#         logging.info("This is a info log.")
#         return func(*args, **kwargs)
#     return wrapper


# def log():  # 带参数的装饰器需要2层装饰器实现,第一层传参数，第二层传函数，每层函数在上一层返回
def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        logFilePath = 'testlog/log.log'  # 日志按日期滚动，保留5天
        logger = logging.getLogger('testlog')
        # logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        # 记录到文件
        handler = TimedRotatingFileHandler(logFilePath, when="d", interval=1, backupCount=5)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        # 输出到控制台
        handler1 = logging.StreamHandler()
        handler1.setFormatter(formatter)
        logger.addHandler(handler1)
        try:
            logger.info('begin running: %s()' % func.__name__)
            logger.info('用例备注: %s' % func.__doc__)
            result = func(*args, **kwargs)
            logger.info(f'执行结果: {result}')
            logger.info('running %s() **end**' % func.__name__)
        except:
            logger.error(traceback.format_exc())
        finally:
            # 清掉handler，避免重复日志打印
            logger.removeHandler(handler)
            logger.removeHandler(handler1)

    return wrapper


@log
def ksp(n, m):
    # print(100 / n)
    pass


if __name__ == '__main__':
    ksp(2, 4)
